/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2012-2020. All rights reserved.
 */

package com.huawei.chengdu.meetingdemo.util;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;

import com.device.idea.meeting.MultiStream.model.LayoutSubWindow;
import com.device.idea.meeting.MultiStream.model.SurfaceViewInfo;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * 类名：ScreenUtil
 */
public final class ScreenUtil {
    private static final String TAG = "ScreenUtil";
    private static final Map<Integer, Integer> SURFACE_VIEWID_MAP = new HashMap<>();
    private static long lastClickTime;

    private static Optional<DisplayMetrics> getRealDisplayMetrics(Context context) {
        if (!(context.getSystemService(Context.WINDOW_SERVICE) instanceof WindowManager)) {
            return Optional.empty();
        }
        WindowManager mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        if (mWindowManager == null) {
            return Optional.empty();
        }
        Display display = mWindowManager.getDefaultDisplay();
        if (display == null) {
            return Optional.empty();
        }
        DisplayMetrics realDisplayMetrics = new DisplayMetrics();
        display.getRealMetrics(realDisplayMetrics);
        return Optional.of(realDisplayMetrics);
    }

    /**
     * 获取实时窗口宽度
     *
     * @param context 上下文
     * @return 实时窗口宽度
     */
    public static int getRealWindowWidth(Context context) {
        return getRealDisplayMetrics(context).get().widthPixels;
    }

    /**
     * 获取实时窗口高度
     *
     * @param context 上下文
     * @return 真实窗口高度
     */
    public static int getRealWindowHeight(Context context) {
        return getRealDisplayMetrics(context).get().heightPixels;
    }

    /**
     * 根据surfaceView 获取绑定的 subwindow 的 viewId
     *
     * @param surfaceView view
     * @return subwindow 的 viewId
     */
    public static int getSurfaceId(SurfaceView surfaceView) {
        if (surfaceView == null) {
            return -1;
        }
        Integer surfaceId = SURFACE_VIEWID_MAP.get(surfaceView.getId());
        return surfaceId == null ? -1 : surfaceId;
    }

    /**
     * 绑定Surface
     *
     * @param subWindow subWindow
     * @param surface surfaceView
     * @return SurfaceViewInfo
     */
    public static SurfaceViewInfo bindSurface(LayoutSubWindow subWindow, SurfaceView surface) {
        SurfaceViewInfo surfaceViewInfo = new SurfaceViewInfo();
        surfaceViewInfo.setViewId(subWindow.getViewId());
        surfaceViewInfo.setSurfaceView(surface);
        SURFACE_VIEWID_MAP.put(surfaceViewInfo.getSurfaceView().getId(), subWindow.getViewId());
        return surfaceViewInfo;
    }

    /**
     * 清理绑定信息
     */
    public static void clearBindInfo() {
        SURFACE_VIEWID_MAP.clear();
    }

    /**
     * 海思芯片问题导致SurfaceView的大小和坐标必现是16的倍数，不然会有黑边，取最接近的16的整数倍的值
     *
     * @param dimensionSize 原始大小
     * @return 最接近的16的整数倍的值
     */
    public static int getSizeIntMulti(int dimensionSize) {
        return BigDecimal.valueOf(dimensionSize)
                .divide(BigDecimal.valueOf(16), 0, BigDecimal.ROUND_HALF_DOWN)
                .multiply(BigDecimal.valueOf(16)).intValue();
    }

    /**
     * 重新设置SurfaceView大小
     *
     * @param parentView SurfaceView的父布局
     * @param subWindow 媒体的原始信息
     * @param surfaceView surfaceView
     */
    public static void resetSurfaceViewSize(View parentView, LayoutSubWindow subWindow, SurfaceView surfaceView) {
        parentView.post(() -> {
            LogUtil.info(TAG + "SourceSize:" + subWindow.getWidth() + "/" + subWindow.getHeight());
            LogUtil.info(TAG + "ViewSize:" + parentView.getWidth() + "/" + parentView.getHeight());
            ViewGroup.LayoutParams layoutParams = surfaceView.getLayoutParams();
            if (!isNeedResetSize(parentView, subWindow)) {
                layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
                layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
                surfaceView.setLayoutParams(layoutParams);
                return;
            }
            double sizePortion = (double) subWindow.getWidth() / (double) subWindow.getHeight();
            if (sizePortion > 16.0 / 9.0) { // 需要按照宽进行缩放
                layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
                layoutParams.height = getSizeIntMulti(
                        parentView.getWidth() * subWindow.getHeight() / subWindow.getWidth());
            } else { // 需要按照高进行缩放
                layoutParams.width = getSizeIntMulti(
                        parentView.getHeight() * subWindow.getWidth() / subWindow.getHeight());
                layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
            }
            LogUtil.info(TAG + "TarSize:" + layoutParams.width + "/" + layoutParams.height);
            surfaceView.setLayoutParams(layoutParams);
        });
    }

    /**
     * 申请悬浮窗权限
     * @param context
     */
    public static void requestFloatWindowRight(Context context) {
        Intent intent=new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.fromParts("package",context.getPackageName(),null));
        context.startActivity(intent);
    }

    private static boolean isNeedResetSize(View parentView, LayoutSubWindow subWindow) {
        if (subWindow.getWidth() <= 0 || subWindow.getHeight() <= 0) {
            return false;
        }
        if (subWindow.getWidth() % 16 == 0 && subWindow.getHeight() % 9 == 0
                && subWindow.getWidth() / 16 == subWindow.getHeight() / 9) {
            return false;
        }
        if (subWindow.getWidth() == parentView.getWidth() && subWindow.getHeight() == parentView.getHeight()) {
            return false;
        }
        return true;
    }

    // 海思芯片问题导致SurfaceView的大小和坐标必现是16的倍数，不然会有黑边，取最接近的16的整数倍的值
    public static int getDimensionSize(int dimension) {
        return BigDecimal.valueOf(dimension)
                .divide(BigDecimal.valueOf(16), 0, BigDecimal.ROUND_HALF_DOWN)
                .multiply(BigDecimal.valueOf(16)).intValue();
    }

    public static boolean isClickFast() {
        boolean isFast = false;
        long currentTime = System.nanoTime();
        long time = currentTime - lastClickTime;
        LogUtil.debug("NoDoubleClickUtil " + "time:" + time);
        if (time < 1000000000L) {
            LogUtil.debug("NoDoubleClickUtil " + "click is fast");
            isFast = true;
        }

        lastClickTime = currentTime;
        return isFast;
    }
}
